<?php
/**
 * pan后台 促销活动管理
 *
 * Author: lyun
 * Date: 2018/7/23
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Admin\Panx;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Admin\Panx\Activity\ActivityStoreRequest;
use App\Http\Requests\Admin\Panx\Activity\ActivityUpdateRequest;
use App\Models\Panx\Activity;
use Illuminate\Http\Request;

class ActivityController extends ApiController
{
    const ROUTES = [
        'index'   => 'api.admin.panx.activity.index',
        'store'   => 'api.admin.panx.activity.store',
        'update'  => 'api.admin.panx.activity.update',
        'destroy' => 'api.admin.panx.activity.destroy',
    ];

    /**
     * 查看促销活动列表
     * @test
     *
     * @param Request $request
     * @return array|\Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $activities = Activity::latest()
            ->paginate($request->per_page?:15);

        return $this->response(compact('activities'));
    }

    /**
     * 添加促销活动
     * @test
     *
     * @param ActivityStoreRequest $request
     * @return array|\Illuminate\Http\Response
     */
    public function store(ActivityStoreRequest $request)
    {
        $activity_data = $this->assembleData($request);

        $stored = Activity::create($activity_data);

        return $this->response(compact('stored'));
    }

    /**
     * 更新促销活动、
     * @test
     *
     * @param ActivityUpdateRequest $request
     * @param $activity_id
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function update(ActivityUpdateRequest $request, $activity_id)
    {
        /** @var Activity $activity */
        $activity = Activity::find($activity_id);
            $this->checkItemExist($activity, '促销活动');

        $activity_data = $this->assembleData($request);

        $updated = $activity->update($activity_data);

        return $this->response(compact('updated'));
    }

    /**
     * 删除促销活动
     * @test
     *
     * @param $activity_id
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function destroy($activity_id)
    {
        /** @var Activity $activity */
        $activity = Activity::find($activity_id);
            $this->checkItemExist($activity, '促销活动');

        $deleted = $activity->delete();

        return $this->response(compact('deleted'));
    }

    /**
     * @param Request|ActivityUpdateRequest|ActivityStoreRequest $request
     * @return array
     */
    private function assembleData(Request $request)
    {
        $data = [
            'name'         => $request->name,
            'activity_url' => $request->activity_url,
            'started_at'   => $request->started_at,
            'ended_at'     => $request->ended_at,
        ];

        if (is_file($request->activity_picture)) {
            $data['activity_picture'] = $request->activity_picture;
        }

        return $data;
    }
}
